﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.UI
{
    public class UIBase : MonoBehaviour
    {
        [SerializeField]
        protected EnUIType mUIType = EnUIType.UIPanel;

        [SerializeField]
        private List<GameObject> mGameObjectList = new List<GameObject>();

        protected void Awake()
        {
            GenerateGameObjectList();
            OnAwake();
        }

        protected virtual void OnAwake() { }

        #region GameObject、Compoent相关
        public GameObject GetGameObject(string pGameObjectName)
        {
            GameObject resultObj = null;

            foreach (GameObject obj in mGameObjectList)
            {
                if (obj.name == pGameObjectName)
                {
                    resultObj = obj;
                    break;
                }
            }

            if (resultObj == null)
            {
                string path = GetFullPath();
                Debug.LogWarning($"Get GameObject <color=yellow>{pGameObjectName}</color> is null. Path is <color=yellow>{path}</color>");
            }
            
            return resultObj;
        }

        public T GetComponent<T>(string pGameObjectName)
        {
            GameObject obj = GetGameObject(pGameObjectName);
            if (obj != null)
            {
                T component = obj.GetComponent<T>();
                if (component != null)
                    return component;
                else
                {
                    string path = GetFullPath();
                    Debug.LogWarning($"GameObject <color=yellow>{pGameObjectName}</color> get Component <color=yellow>{typeof(T).Name}</color> is not exist. Path is <color=yellow>{path}</color>");
                }
            }

            return default;
        }

        private string GetFullPath()
        {
            string path = transform.name;

            Transform parentTransform = transform.parent;
            while (parentTransform != null)
            {
                path = $"{parentTransform.name}/{path}";
                parentTransform = parentTransform.parent;
            }

            return path;
        }
        #endregion

        #region 编辑器相关
        protected virtual void OnValidate()
        {
            GenerateGameObjectList();
        }

        private void GenerateGameObjectList()
        {
            mGameObjectList.Clear();

            UIElement[] allUIComponents = this.gameObject.GetComponentsInChildren<UIElement>(true);
            foreach (UIElement uiComponent in allUIComponents)
            {
                if (mUIType == uiComponent.mToUIType && this.gameObject != uiComponent.gameObject)
                    mGameObjectList.Add(uiComponent.gameObject);
            }
        }
        #endregion
    }
}